class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
    }
    // 得到主表数据
    GetEntityData() {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['typeFlag'] = '1';                                       // 副资材单耗
        item['catalogueId'] = $.trim($("#CatalogueId").val());        // 所属单耗目录
        item['productId'] = $.trim($("#ProductId").val());            //       
        item['styleNo'] = $.trim($("#StyleNo").val());                // 款号（为了日志记载用）
        item['dateOfFilling'] = $.trim($("#DateOfFilling").val());    // 填写日期       
        item['designedBy'] = formatNullInputValue($.trim($("#DesignedBy").val()));   // 设计员
        item['gradedBy'] = formatNullInputValue($.trim($("#GradedBy").val()));       // 单耗员
        item['icLabDipIndication'] = formatNullInputValue($.trim($("#IcLabDipIndication").val()));          // IC色样
        item['embroideryLaceAndOther'] = formatNullInputValue($.trim($("#EmbroideryLaceAndOther").val()));  // 刺绣
        item['notes'] = formatNullInputValue($.trim($("#Notes").val()));
        item['description'] = formatNullInputValue($.trim($("#Description").val()));   // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());
        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        $("#CatalogueId").val(item.catalogueId);
        $("#ProductId").val(formatNullData(item.productId));
        $("#StyleNo").val(item.styleNo);
        $("#ProductName").val(item.productName);
        $("#CustomerName").val(item.customerName);
        $("#DateOfFilling").val(item.dateOfFilling);
        $("#DesignedBy").val(item.designedBy);
        $("#DesignedByName").val(item.designedByName);
        $("#GradedBy").val(item.gradedBy);
        $("#GradedByName").val(item.gradedByName);
        $("#IcLabDipIndication").val(item.icLabDipIndication);
        $("#EmbroideryLaceAndOther").val(item.embroideryLaceAndOther);
        $("#Notes").val(item.notes);
        $("#UpdatedByName").val(item.updatedByName);
        $("#UpdatedDate").val(formatNullData(item.updatedDate));
        $("#Description").val(item.description);
        $("#MrpStatus").val(item.mrpStatus);           // 调达表审核状态
        $("#QuotedFlag").val(item.quotedFlag);         // 是否被引用

        // 得到相关配色方案用成品色
        _InstancePageLines.productColourNode = data.ProductColourNode;
        //重建明细表头
        _InstancePageLines.BuildDataTableHeader();
        // 显示明细数据
        _InstancePageLines.BuildDataTable(data.LinesList);

        // 编辑状态时不允许更改款号
        $("#ChoiceStyleNo").attr("onclick", "");
        $("#StyleNo").css({"cursor": "default"});

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;
        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });

        /*
         if (parseInt($("#QuotedFlag").val()) === 1) {
         $("Button.act__save").hide();
         $("span.act__delete").removeClass("trash");
         $("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
         $("#remark").hide();
         }*/

        $("#StyleNo").focus();
    }
    Save() {
        // 如果有主表ID，则编辑否则新增
        if (parseInt($("#HeaderId").val()) === 0) {
            this.saveUrl = "/tech/piece_yardage_onesize/header/insert.html";
        } else {
            this.saveUrl = "/tech/piece_yardage_onesize/header/update.html";
        }
        super.Save(function (data, _this) {
            if (data !== {}) {
                if (parseInt(_this.pageStatus) === 1) {
                    $("#HeaderId").val(data.HeaderKey);   // 设置刚才插入的记录ID
                    _this.dataId = data;
                    $("#Action").val(2);
                    _this.pageStatus = 2;
                    // 得到相关配色方案用成品色
                    _InstancePageLines.productColourNode = data.ProductColourNode;
                    // 显示明细数据
                    _InstancePageLines.BuildDataTableHeader();
                    _InstancePageLines.BuildDataTable(data.LinesList);
                    _InstancePageLines.AutoAdjustTableHeightForLines();

                    $("#panelSlave").show();
                }
            }
        });
    }
    New() {
        super.New();
        $("#HeaderId").val(0);
        $("#panelSlave").hide();
        // 新增状态时允许更改款号
        let _event_onclick = '_InstancePageHeader.DoChoiceStyleNo()';
        $("#ChoiceStyleNo").attr("onclick", _event_onclick);
        $("#StyleNo").css({"cursor": "pointer"});

        // 默认设置一些值
        $("#DesignedBy").val($.trim($("#UserId").val()));  // 设计者默认为登录者
        $("#DesignedByName").val($("#UserName").val());
        $("#DateOfFilling").val(getCurrentDate());
        $("#UpdatedDate").val(getCurrentDate());
        $("#UpdatedByName").val($("#UserName").val());
        $("#StyleNo").empty();
        $('#tabData11 tbody').empty();
        $('#tabData12 tbody').empty();
        _InstancePageLines.rows = 0;
        //自适应高度
        _InstancePageLines.AutoAdjustTableHeightForLines();

        $("#StyleNo").focus();
    }
    // 以下为选择框
    DoChoiceDesigner() {
        let _choice = new CommonChoice();
        _choice.DoChoiceUser(0, '设计担当', '设计', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#DesignedByName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#DesignedBy").val(data[0]);
                $("#DesignedByName").val(data[1]);
            }
        });
        $("#DesignedByName").focus();
    }
    DoChoiceStyleNo() {
        let _choice = new CommonChoice();
        _choice.DoChoiceProduct(0, '选择款号', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#StyleNo").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#ProductId").val(data[0]);
                $("#StyleNo").val(data[1]);
                $("#ProductName").val(data[2]);
                $("#CustomerName").val(data[5]);
                // 根据款号得到生产指示书的备注，并保存到注意事项中
                super.DoAjax(data[1], "/trade/production_instruction/fetchByStyleNo.html", function (data, _this) {
                    if (data !== null) {
                        $("#Notes").val(data.description === null ? "" : data.description);
                    }
                });
            }
        });
        $("#StyleNo").focus();
    }
    DoPrintPreview() {
        window.open(parent.basePath + this.printUrl + "?id=" + $("#HeaderId").val());
    }
    Expand() {
        super.Expand(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
    /* 折叠 */
    Collapse() {
        super.Collapse(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
        $("#remark").show();
    }
    HidePageElement() {
        //$("Button.act__save").hide();
        //$("span.act__delete").removeClass("trash");
        //$("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
        //$("#remark").hide();
    }
}

class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.$input = null;
        this.productColourNode = [];
        this.clipboard = []; // 剪切板
        this.selectedItemList = [];
    }
    BuildDataTableHeader() {
        // 形成颜色表头 
        let _th = '<th class="edit__column">客户用量</th>';
        _th += '<th class="edit__column">工厂用量</th>';
        _th += '<th class="edit__column">套裁用量</th>';
        _th += '<th style="text-align:center;">单位</th>';
        let _colWidth = 75 * 3 + 50;
        let _col = '<col style="width:75px;" />';
        _col += '<col style="width:75px;" />';
        _col += '<col style="width:75px;" />';
        _col += '<col style="width:35px;" />';
        if ((this.productColourNode !== null) && (this.productColourNode.length > 0)) {
            for (let i = 0; i < this.productColourNode.length; i++) {
                _col += '<col style="width:130px;" />';
                _colWidth += 130;
                _th += '<th class="edit__column">' + this.productColourNode[i].productColourName + '</th>';
            }
        }
        _col += '<col style="width:75px;" />';
        _th += '<th style="text-align:center;" class="edit__column">备料来源</th>';
        _colWidth += 75;
        let w = $(window).width() - 767 - 16 - 17;
        let _w_desc = (w - _colWidth) < 400 ? 400 : (w - _colWidth);
        _col += '<col style="' + _w_desc + 'px;" />';
        _th += '<th class="edit__column">备注</th>';
        _colWidth += _w_desc;
        $("#tabHeader12").css({width: _colWidth});
        $("#tabData12").css({width: _colWidth});
        $("#tabHeader12 thead tr").empty();
        $("#tabHeader12 colgroup").empty();
        $("#tabData12 colgroup").empty();
        $("#tabHeader12 colgroup").html(_col);
        $("#tabData12 colgroup").html(_col);
        $("#tabHeader12 thead tr").html(_th);
    }
    BuildDataTable(result) {
        $('#tabData11 tbody').empty();
        $('#tabData12 tbody').empty();
        // 得到数据列表
        if (result === null || result.length === 0) {
            $('#loading').hide();
            this.rows = 0;
            // 自适应高度
            this.AutoAdjustTableHeightForLines();
            return false;
        }
        let content01 = '';
        let content02 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            if (result[i].poQuotedFlag === true) {
                content01 += '<tr _mash_quoted="1" style="background-color:#606060; color:#fff;" _mash_id="' + id + '" _mash_material_id="' + result[i].materialId + '">';
                content01 += '<td></td>';
                content01 += '<td></td>';
                content01 += '<td style="text-align:center;">' + formatNullData(result[i].orderNo) + '</td>';
            } else {
                if (result[i].mrpQuotedFlag === true) {
                    content01 += '<tr _mash_quoted="1" _mash_id="' + id + '" _mash_material_id="' + result[i].materialId + '">';
                    content01 += '<td></td>';
                    content01 += '<td></td>';
                    content01 += '<td style="text-align:center;">' + formatNullData(result[i].orderNo) + '</td>';
                } else {
                    content01 += '<tr _mash_quoted="0" _mash_id="' + id + '" _mash_material_id="' + result[i].materialId + '">';
                    content01 += '<td><label style="margin-left:3px;" class="btn" for="R-' + id + '"><input id="R-' + id + '" name="_check_row" type="checkbox" onclick="_InstancePageLines.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + id + '"/><i></i><span></span></label></td>';
                    // 删除权限判断
                    if ($("#ActionAcl_4").length === 0 || parseInt($("#ActionAcl_4").val() === 0)) {
                        content01 += '<td></td>';
                    } else {
                        content01 += '<td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageLines.DoDeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
                    }
                    content01 += '<td style="text-align:center;">' + formatNullData(result[i].orderNo) + '</td>';
                }
            }
            content01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
            content01 += '<td>' + formatNullData(result[i].supplierName) + '</td>';
            content01 += '<td class="edited-cell" style="text-overflow:ellipsis;" title="' + formatNullData(result[i].partOfNeed) + '">' + formatNullData(result[i].partOfNeed) + '</td>';
            if (result[i].poQuotedFlag === false) {
                content01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
            } else {
                content01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
            }
            content01 += '<td class="edited-cell">' + formatNullData(result[i].specification) + '</td>';
            content01 += '</tr>';

            if (result[i].poQuotedFlag === true) {
                content02 += '<tr style="background-color:#606060; color:#fff;">';
            } else {
                content02 += '<tr>';
            }
            if (result[i].poQuotedFlag === false) {
                content02 += '<td class="edited-cell">' + formatNullData(result[i].customerPieceYardage === 0 ? null : result[i].customerPieceYardage) + '</td>';
                content02 += '<td class="edited-cell">' + formatNullData(result[i].factoryPieceYardage === 0 ? null : result[i].factoryPieceYardage) + '</td>';
                content02 += '<td class="edited-cell">' + formatNullData(result[i].suitCutPieceYardage === 0 ? null : result[i].suitCutPieceYardage) + '</td>';
                content02 += '<td style="text-align:center;" _mash_uom_id="' + result[i].uomId + '">' + formatNullData(result[i].uomName) + '</td>';
                // 显示颜色搭配情况
                if (this.productColourNode !== null) {
                    for (let j = 0; j < this.productColourNode.length; j++) {
                        let _productColourId = this.productColourNode[j].productColourId.toString();
                        let _t = false;
                        $.each(result[i].colourSchema, function (index, data) {
                            if (data.ProductColourId === _productColourId) {
                                content02 += '<td class="edited-cell">' + formatNullData(data.MaterialColour) + '</td>'; // 搭配的材料色
                                _t = true;
                                return false;
                            }
                        });
                        if (_t === false)
                            content02 += '<td class="edited-cell"></td>'; // 搭配的材料色
                    }
                }
            } else {
                content02 += '<td>' + formatNullData(result[i].customerPieceYardage === 0 ? null : result[i].customerPieceYardage) + '</td>';
                content02 += '<td>' + formatNullData(result[i].factoryPieceYardage === 0 ? null : result[i].factoryPieceYardage) + '</td>';
                content02 += '<td>' + formatNullData(result[i].suitCutPieceYardage === 0 ? null : result[i].suitCutPieceYardage) + '</td>';
                content02 += '<td style="text-align:center;" _mash_uom_id="' + result[i].uomId + '">' + formatNullData(result[i].uomName) + '</td>';
                // 显示颜色搭配情况
                if (this.productColourNode !== null) {
                    for (let j = 0; j < this.productColourNode.length; j++) {
                        let _productColourId = this.productColourNode[j].productColourId.toString();
                        let _t = false;
                        $.each(result[i].colourSchema, function (index, data) {
                            if (data.ProductColourId === _productColourId) {
                                content02 += '<td>' + formatNullData(data.MaterialColour) + '</td>'; // 搭配的材料色
                                _t = true;
                                return false;
                            }
                        });
                        if (_t === false)
                            content02 += '<td></td>'; // 搭配的材料色
                    }
                }
            }
            if (result[i].quotedFlag === false) {
                content02 += '<td class="edited-cell" style="text-align:center;" _mash_type_id="' + result[i].materialSourceTypeId + '">' + formatNullData(result[i].materialSourceTypeName) + '</td>';    // 物料来源
            } else {
                content02 += '<td style="text-align:center;" _mash_type_id="' + result[i].materialSourceTypeId + '">' + formatNullData(result[i].materialSourceTypeName) + '</td>';    // 物料来源
            }
            content02 += '<td class="edited-cell">' + formatNullData(result[i].description) + '</td>';                 // 备注
            content02 += '</tr>';
            $('#tabData11 tbody').append(content01);
            $('#tabData12 tbody').append(content02);
            content01 = '';
            content02 = '';

        }
        setTwoTableRowColor("tabData11", "tabData12");
        $("#CheckAll").prop("checked", false);

        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();

        let cell_id = "_cell__field";
        let cell_name = "__cell__field";
        let _this = this;
        $('#tabData11 tbody tr').find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                case 6:
                    $(this).attr("_old_val", $(this).text());
                    OnCellClickEvent($(this), cell_id, cell_name, 0);
                    break;
                default:
                    OnCellClickEvent($(this), cell_id, cell_name, 0);
                    break;
            }
        });
        let _index = $('#tabData12 tbody tr').find('td:last').index() - 1;
        $('#tabData12 tbody tr').find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                case _index:
                    OnCellPopupEditEvent($(this), cell_id, cell_name, ($input) => {
                        _this.DoChoiceMaterialSourceType($input);
                    });
                    break;
                default:
                    OnCellClickEvent($(this), cell_id, cell_name, 0);
                    break;
            }
        });

        // 拖动表格行改变显示顺序
        $("#tabData11 tbody").wxdragsort({
            dragWrapper: $("#tabLinesList"),
            placeHolderWrapper: $("#tabLinesList"),
            parentobj: $("#tabLinesList"),
            syncobj: "tabData12",
            dragColumnIndex: 2,
            dragEnd: () => {
                this.UpdateLinesOrder();
            }
        });

        /*
         if ((parseInt($("#UserId").val()) === parseInt($("#DesignedBy").val())) || ($("#RoleName").val().indexOf("系统管理员") !== -1)) {
         // 设置回车处理事件
         $("#panelSlaveData_01").keyup((event) => {
         if (event.keyCode === 13) {
         this.ClearGridMaterialNoError();
         $("#ButSaveLines").focus();
         this.SaveLines();
         event.stopPropagation();
         }
         });
         }*/

        $("#loading").hide();
    }
    // 拖动改变序号
    UpdateLinesOrder() {
        // 第一步，根据当前顺序，重新设置行号
        $("#tabData11 tbody").find("tr").each(function (index) {
            $(this).find("td").eq(2).html(index + 1);
        });

        // 第二步，同步到后台数据库
        let itemResult = [];
        $('#tabData11 tbody').find("tr").each(function (index) {
            let _orderNo = $.trim($(this).find('td').eq(2).text());   // 顺序号
            let item = {};
            item['headerId'] = $("#HeaderId").val();
            item['linesId'] = $.trim($(this).attr("_mash_id"));
            item['orderNo'] = parseInt(_orderNo);
            itemResult.push(item);
        });

        // 更新后台对应的序号
        super.DoAjax(itemResult, "/tech/piece_yardage_onesize/lines/updateLinesOrder.html", function (data, _this) {
            if (data.LinesList !== undefined) {
                // 刷新明细
                _this.BuildDataTable(data.LinesList);
            }
            ShowSuccessMessagePanel("改变顺序完成。");
        });
    }
    // 得到要保存的数据
    GetLinesData() {
        let _this = this;
        let jsonResult = [];
        // 得到修改过数据
        $('#tabData12 tbody').find("tr").each(function (index) {
            let $tr2 = $(this);
            let $tr1 = $('#tabData11 tbody').find("tr").eq(index);
            if ($tr2.find("td.dirty").length || $tr1.find("td.dirty").length) {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = $tr1.attr("_mash_id");
                item['materialId'] = $tr1.attr("_mash_material_id");
                item['poQuotedFlag'] = parseInt($tr1.attr("_mash_quoted"));
                item['orderNo'] = formatNullInputValue($.trim($tr1.find('td').eq(2).text())) === null ? 0 : $.trim($tr1.find('td').eq(2).text());         // 顺序
                item['partOfNeed'] = formatNullInputValue($.trim($tr1.find('td').eq(5).text())) === null ? '' : $.trim($tr1.find('td').eq(5).text());     // 使用部位
                if ($tr1.find('td').eq(6).hasClass("dirty")) {
                    item['materialCode'] = formatNullInputValue($.trim($tr1.find('td').eq(6).text()));             // 料号
                } else {
                    item['materialCode'] = null;
                }
                item['specification'] = formatNullInputValue($.trim($tr1.find('td').eq(7).text()));                // 规格
                item['customerPieceYardage'] = $.trim($tr2.find('td').eq(0).text()) === '' ? 0 : $.trim($tr2.find('td').eq(0).text());
                item['factoryPieceYardage'] = $.trim($tr2.find('td').eq(1).text()) === '' ? 0 : $.trim($tr2.find('td').eq(1).text());
                item['suitCutPieceYardage'] = $.trim($tr2.find('td').eq(2).text()) === '' ? 0 : $.trim($tr2.find('td').eq(2).text());
                //item['uomId'] = formatNullInputValue($.trim($tr2.find('td').eq(3).attr("_mash_uom_id")));   // 计量单位
                if ($tr2.find('td:last').prev().hasClass("dirty")) {
                    item['materialSourceTypeId'] = $.trim($tr2.find('td:last').prev().attr("_mash_type_id"));   // 备料来源ID
                }
                item['description'] = formatNullInputValue($.trim($tr2.find('td').last().text()));                // 备注
                item['updatedBy'] = $("#UserId").val();

                // 取得材料配色表
                let _colourSchemaList = [];
                for (let j = 0; j < _this.productColourNode.length; j++) {
                    let _item = {};
                    _item['headerId'] = $("#HeaderId").val();
                    _item['parentLinesId'] = $tr1.attr("_mash_id");
                    _item['productColourId'] = parseInt(_this.productColourNode[j].productColourId);
                    _item['materialColour'] = formatNullInputValue($.trim($tr2.find('td').eq(j + 4).text()));
                    _colourSchemaList.push(_item);
                }
                item['colourSchemaList'] = _colourSchemaList;

                jsonResult.push(item);
            }
        });
        console.info(JSON.stringify(jsonResult));
        return JSON.stringify(jsonResult);
    }
    SaveLines() {
        if ($('#tabData11 tbody tr').find("td").eq(6).hasClass("dirty")) {
            showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要改变当前材料吗？', () => {
                this.OnSaveLines();
            }, () => {
                return false;
            });
        } else {
            this.OnSaveLines();
        }
    }
    OnSaveLines() {
        //step 1、进行页面验证，失败则返回
        let success_01 = CheckGridInput();
        if (!success_01)
            return;

        super.SaveLines("/tech/piece_yardage_onesize/lines/update.html", function (data, _this) {
            if (data.Success === undefined) {
                ShowSuccessMessagePanel("保存成功。");
            } else {
                if (data.Success) {
                    // 刷新明细
                    _this.BuildDataTable(data.LinesList);
                    ShowSuccessMessagePanel("保存成功。");
                } else {
                    for (let i = 0; i < data.ErrRowNo.length; i++) {
                        $('#tabData11 tbody').find("tr").each(function () {
                            if (parseInt($(this).find("td").eq(2).text()) === parseInt(data.ErrRowNo[i])) {
                                $(this).find('td').eq(6).addClass("error");
                                $(this).find('td').eq(6).attr('title', "料号有错误或未审核的材料。");
                            }
                        });
                    }
                    ShowErrorMessagePanel("料号有错误或未审核的材料。");
                }
            }
        });
    }
    //删除行
    DoDeleteLines($self) {
        // 为了防止在增加材料时之前修改过的内容丢失，所以要首先保存一下
        if ($('#tabData11 tbody tr').find("td.dirty").length > 0 || $('#tabData12 tbody tr').find("td.dirty").length > 0) {
            showModal(370, 140, '系统信息', '', null, null, 1, "数据有更新，是否需要保存？", () => {
                this.SaveLines();
            }, () => {
                this.OnDeleteLines($self);
            });
        } else {
            this.OnDeleteLines($self);
        }
    }
    OnDeleteLines($self) {
        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['LinesId'] = $self.parent().parent().attr("_mash_id");
        params['DeletedBy'] = $.trim($("#UserId").val());
        params['LinesData'] = "款号：" + $("#StyleNo").val() +
                "　料号：" + $self.parent().parent().find("td").eq(6).text() +
                "　使用部位：" + $self.parent().parent().find("td").eq(5).text();
        this.DeleteLines(params, "/tech/piece_yardage_onesize/lines/delete.html", function (data, _this) {
            if (data.LinesList !== undefined) {
                // 刷新明细
                _this.BuildDataTable(data.LinesList);
            }
            ShowSuccessMessagePanel("删除成功。");
        });
    }
    // 批量删除
    DoBatchDeleteLines() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择要删除的数据。");
            return false;
        }

        this.BatchDeleteLines('/tech/piece_yardage_onesize/lines/batch_delete.html', function (data, $self) {
            // 刷新明细
            $self.BuildDataTable(data);
            $("#CheckAll").prop("checked", false);
            ShowSuccessMessagePanel("批量删除完成。");
        });
    }
    // 增加明细
    NewLines() {
        // 为了防止在增加材料时之前修改过的内容丢失，所以要首先保存一下
        if ($('#tabData11 tbody tr').find("td.dirty").length > 0 || $('#tabData12 tbody tr').find("td.dirty").length > 0) {
            showModal(370, 140, '系统信息', '', null, null, 1, "数据有更新，是否需要保存？", () => {
                this.SaveLines();
            }, () => {
                this.DoInsertMaterial();
            });
        } else {
            this.DoInsertMaterial();
        }
    }
    DoInsertMaterial() {
        let _choice = new CommonChoice();
        _choice.DoChoiceMaterial(1, '选择材料', (data) => {
            if (data) {
                let new_lines = [];
                for (let i = 0; i < data.length; i++) {
                    let item = {};
                    item['headerId'] = parseInt($("#HeaderId").val());
                    item['materialId'] = parseInt(data[i].materialId);
                    item['createdBy'] = parseInt($.trim($("#UserId").val()));
                    item['updatedBy'] = parseInt($.trim($("#UserId").val()));
                    if ($("#tabData11 tbody tr.row__clicked").length) {
                        // 得到当前选择行的序号，为了插入新行做准备
                        item['orderNo'] = parseInt($("#tabData11 tbody tr.row__clicked").find('td').eq(2).text());
                    } else {
                        item['orderNo'] = null;
                    }

                    new_lines.push(item);
                }
                // 根据所选材料，增加明细表记录
                super.DoAjax(new_lines, "/tech/piece_yardage_onesize/lines/insert.html", function (data, _this) {
                    if (data !== null) {
                        _this.BuildDataTable(data);
                        ShowSuccessMessagePanel("材料增加完成。");
                    }
                });
            }
        });
    }
    // 批量选择的数据(类中data:this.GetCheckedLinesData)
    GetCheckedLinesData() {
        let choiced_data = [];
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = $(this).parent().parent().parent().attr("_mash_id");
                item['deletedBy'] = $.trim($("#UserId").val());
                choiced_data.push(item);
            });
        }
        return JSON.stringify(choiced_data);
    }
    // 通过选择的行得到料号，然后弹出材料选择窗口供选择类似的材料（用料号前8位作为条件）
    DoUpdateRowByMaterialCode() {
        if (parseInt($("tr.row__clicked").attr("_mash_quoted")) === 1) {
            ShowErrorMessagePanel('当前行材料已经被采购无法进行更改。');
            return;
        }
        if ($("tr.row__clicked").length > 0) {
            let _choice = new CommonChoice();
            _choice.DoChoiceMaterial('0&materialCode=' + $("#tabData11 tr.row__clicked td").eq(6).text(), '选择材料', (data) => {
                if (data) {
                    let $tr1 = $("#tabData11 tr.row__clicked");
                    let $tr2 = $("#tabData12 tbody tr").eq($tr1.index());
                    let _materialId = data[0];

                    showModal(350, 140, '确认', '', null, null, 1, '请问，确定要改变当前材料吗？', () => {
                        this.OnUpdateRowByMaterialId($tr1.attr("_mash_id"), _materialId);
                    });
                }
            });
        } else {
            ShowErrorMessagePanel('请选择要更改的明细数据行。');
        }
    }
    OnUpdateRowByMaterialId(linesId, materialId) {
        let criterion = {};
        criterion['HeaderId'] = parseInt($("#HeaderId").val());
        criterion['LinesId'] = linesId;
        criterion['MaterialId'] = materialId;
        criterion['UpdatedBy'] = parseInt($("#UserId").val());
        super.DoAjax(criterion, "/tech/piece_yardage_onesize/lines/updateLinesByMaterialId.html", function (data, $self) {
            let $tr1 = $("#tabData11 tr.row__clicked");
            let $tr2 = $("#tabData12 tr.row__clicked");
            if (data.Success) {
                $tr1.attr("_mash_material_id", data.MaterialId);
                $tr1.find("td").eq(3).text(data.MaterialName);    // 料名
                $tr1.find("td").eq(6).text(data.MaterialCode);
                $tr1.find("td").eq(7).text(data.Specification);   // 规格
                $tr1.find("td").eq(4).text(data.SupplierName);    // 供应商
                $tr2.find("td").eq(3).attr("_uomId", data.UomId); // 计量单位标识
                $tr2.find("td").eq(3).text(data.UomName);         // 计量单位名
                if ($(".cell")) {
                    $(".cell").remove();
                    $tr1.find("td").eq(6).removeClass("dirty");
                }
                ShowSuccessMessagePanel("材料改变成功。");
            } else {
                if ($(".cell")) {
                    $(".cell").remove();
                    $tr1.find("td").eq(6).removeClass("dirty");
                }
                $tr1.find("td").eq(6).text($tr1.find("td").eq(6).attr("_old_val"));  // 这个等于撤销功能
                ShowErrorMessagePanel("料号输入错误。");
            }
        });
    }
    // 引入单耗明细 
    ImportLinesFromOtherBom() {
        let _choice = new CommonChoice();
        _choice.DoChoiceBomLines(0, 0, '引入单耗明细', (data) => {
            if (data) {
                let item = {};
                item['HeaderId'] = parseInt($("#HeaderId").val());
                item['ImportedBomHeaderId'] = parseInt(data[0]);
                item['MaxOrderNo'] = parseInt($.trim($("#tabData11 tr:last").find("td").eq(2).text()) === '' ? 0 : $.trim($("#tabData11 tr:last").find("td").eq(2).text()));
                item['CreatedBy'] = parseInt($.trim($("#UserId").val()));
                item['UpdatedBy'] = parseInt($.trim($("#UserId").val()));
                super.DoAjax(item, "/tech/piece_yardage_onesize/lines/importLinesFromOtherBom.html", (data, _this) => {
                    if (data !== null) {
                        // 得到相关配色方案用成品色
                        _this.productColourNode = data.ProductColourNode;
                        //重建明细表头
                        _this.BuildDataTableHeader();
                        // 显示明细数据
                        _this.BuildDataTable(data.LinesList);
                        ShowSuccessMessagePanel('引入完成。');
                    }
                });
            }
        });
    }
    //复制行
    CopyRow() {
        if ($("#tabData11 tr.row__clicked").length > 0) {
            //先清空
            this.clipboard.splice(0, this.clipboard.length);
            let $tr1 = $("#tabData11 tbody tr.row__clicked");
            let $tr2 = $("#tabData12 tbody tr").eq($tr1.index());

            this.clipboard.push($tr1.attr("_mash_id"));
            this.clipboard.push($tr1.attr("_mash_material_id"));
            this.clipboard.push($.trim($tr1.find('td').eq(7).text()));               // 规格
            this.clipboard.push($.trim($tr2.find('td').eq(3).attr("_mash_uom_id"))); // 计量单位

            ShowSuccessMessagePanel('已经拷贝当前选择的数据到剪切板。');
        } else {
            ShowErrorMessagePanel('请选择要拷贝的明细数据行。');
        }
    }
    //粘贴行
    PosteRow() {
        if (this.clipboard === null || this.clipboard.length === 0) {
            ShowErrorMessagePanel('剪切板没有数据。');
            return false;
        }
        let item = {};
        item['HeaderId'] = parseInt($("#HeaderId").val());
        item['CopiedLinesId'] = this.clipboard[0];
        item['MaterialId'] = parseInt(this.clipboard[1]);
        item['Specification'] = formatNullInputValue(this.clipboard[2]);
        item['UomId'] = parseInt(this.clipboard[3]);
        item['CreatedBy'] = parseInt($.trim($("#UserId").val()));
        item['UpdatedBy'] = parseInt($.trim($("#UserId").val()));
        if ($("#tabData11 tbody tr.row__clicked").length) {
            item['OrderNo'] = parseInt($("#tabData11 tbody tr.row__clicked").find('td').eq(2).text());
        } else {
            item['OrderNo'] = null;
        }

        // 粘贴数据
        super.DoAjax(item, "/tech/piece_yardage_onesize/lines/paste.html", function (data, $self) {
            if (data !== null) {
                // 刷新明细记录                       
                $self.BuildDataTable(data);
                ShowSuccessMessagePanel('粘贴数据完成。');
            }
        });
    }
    // 批量更改材料色
    BatchUpdateMaterialColour() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择要更改的数据。");
            return false;
        }

        showModal(495, 268, '更改材料颜色', parent.basePath + '/tech/piece_yardage_onesize/lines/material_colour/edit.html', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }

            // 清空选择的数据
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    // 编辑搭配用成品色
    EditProductColour() {
        showModal(495, 538, '编辑成品颜色', parent.basePath + '/tech/piece_yardage_onesize/lines/product_colour/edit.html', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            // 清空选择的数据
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    // 弹出颜色的选择窗口
    DoChoiceColour($input) {
        this.$input = $input;
        let _choice = new CommonChoice();
        _choice.DoChoiceColour(0, (data) => {
            if (data === false) {
                this.$input.focus();
            } else {
                this.$input.parent().attr("_mash_colour_id", data[0]);
                this.$input.val(data[2]);   // 色号
                this.$input.focus();
            }
        });
    }
    // 选择采购类型（备料来源）
    DoChoiceMaterialSourceType($input) {
        this.$input = $input;
        let _choice = new CommonChoice();
        _choice.DoChoiceMaterialSourceType(0, "选择备料来源", (data) => {
            if (data === false) {
                this.$input.focus();
            } else {
                this.$input.parent().attr("_mash_type_id", data[0]);
                this.$input.val(data[1]);
                this.$input.focus();
            }
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        let _this = this;
        let key = $self.val();
        super.AdjustRowStatus($self, function ($row, index) {
            $('#tabData12 tbody tr:eq(' + index + ')').addClass("row__selected");
            // 设置删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
            let item = {};
            item['linesId'] = key;
            _this.selectedItemList[key] = item;
        }, function ($row, index) {
            $('#tabData12 tbody tr:eq(' + index + ')').removeClass("row__selected");
            // 设置删除按钮有效
            let _event_delete_onclick = '_InstancePageLines.DeleteLines($(this))';
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_delete_onclick);
            delete _this.selectedItemList[key];
        });
    }
    // 恢复选择状态
    ResetSelectRowStatus() {
        let _this = this;
        $("#tabData11 tbody").find("tr").each(function (index) {
            let key = $(this).attr("_mash_id");
            if (_this.selectedItemList[key] !== undefined) {
                $(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row']").eq(0).prop('checked', true);
                $(this).addClass("row__selected");

                $('#tabData12 tbody tr:eq(' + index + ')').addClass("row__selected");
                // 设置删除按钮失效
                $(this).children('td').eq(1).children('span').eq(0).attr("onclick", "");
            }
        });
        // 设置选择全部的状态
        let n = $("input[type='checkbox'][name='_check_row']:checked").length;
        if (n < $("#tabData11 tbody").find("tr").length || n === 0) {
            $("#CheckAll").prop("checked", false);
        } else {
            $("#CheckAll").prop("checked", true);
        }
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = $("#divH11").offset().top + 26;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        let _rc = Math.floor((h - _tabTop - 25) / 25);
        let _dh = _rc * 25 + 17;
        let _rowH = this.rows * 25 + 17; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD11").css({"max-height": _dh - 17, height: _dh - 17});
        $("#divD12").css({"max-height": _dh + 1, height: _dh + 1});
    }
    ScrollTo() {
        $('#divH12').scrollLeft($('#divD12').scrollLeft());
        $('#divD11').scrollTop($('#divD12').scrollTop());
    }
    // 清除料号错误
    ClearGridMaterialNoError() {
        $('#tabData11 tbody').find("tr").each(function (index) {
            $(this).find('td').eq(6).attr('title', '');
            $(this).find('td').eq(6).removeClass("error");
        });
    }
}

var _InstancePageHeader = null;
var _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();

    let piece_yardage_onesize_auxiliary_list_result = $.cookie("piece_yardage_onesize_auxiliary_list_result") === undefined ? "" : $.cookie("piece_yardage_onesize_auxiliary_list_result");
    let _pageListData = [];
    if (piece_yardage_onesize_auxiliary_list_result !== "") {
        _pageListData = piece_yardage_onesize_auxiliary_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }
    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/tech/piece_yardage_onesize/auxiliary/list.html",
            "/tech/piece_yardage_onesize/fetchByKey.html",
            "/tech/piece_yardage_onesize/header/insert.html",
            "/tech/piece_yardage_onesize/auxiliary/export.html",
            "/tech/piece_yardage_onesize/print.html");

    _InstancePageLines = new MyPageLines();
    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelData"});

    window.laydate.render({
        elem: '#DateOfFilling',
        theme: '#393D49',
        trigger: 'click'
    });

    $("#hPanelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-up")) {
            _InstancePageHeader.Collapse();
        } else {
            _InstancePageHeader.Expand();
        }
    });

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let wLeftList = 803; //左边列表固定宽度
    let w = $(window).width();

    $("#divH12").css({width: w - 16 - wLeftList - 17});
    $("#divD12").css({left: -1, width: w - wLeftList - 15});

    if (_InstancePageLines !== null)
        _InstancePageLines.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _StyleNo: "required",
            _DateOfFilling: {
                dateISO: true,
                required: true
            },
            _Description: "required"
        },
        messages: {
            _StyleNo: "请填写款号。",
            _DateOfFilling: {
                dateISO: "请填写正确的填表日期。",
                required: "请填写填表日期。"
            },
            _Description: "请填写备注。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});

// 验证输入
function CheckGridInput() {
    $('#tabData11 tbody').find("tr").each(function (index) {
        let $tr1 = $('#tabData11 tbody').find("tr").eq(index);
        let _orderno = $.trim($tr1.find('td').eq(2).text()).length > 0 ? $.trim($tr1.find('td').eq(2).text()) : 0; // 序号
        let _materialcode = $.trim($tr1.find('td').eq(6).text());

        if (_orderno !== 0) {
            if (!isNumber(_orderno)) {
                GridCheckErrHandle($tr1, 2, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr1, 2);
            }
        }

        if (_materialcode === "") {
            GridCheckErrHandle($tr1, 6, '请输入材料号。');
        } else {
            GridCheckSuccessHandle($tr1, 6);
        }
    });

    if ($('#tabData11 tbody').find('td.error').length > 0 || $('#tabData12 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}